import { Component, OnInit } from '@angular/core';
import { JsonApiService } from "app/core/api/json-api.service"; //http请求配置引入
import { Router, ActivatedRoute } from "@angular/router"; //路由引入
import { config } from '../../shared/smartadmin.config';
declare var $: any;
@Component({
	selector: 'sa-user-limit-control',
	templateUrl: './user-limit.component.html',
})
export class UserLimitControlComponent implements OnInit {
	
	validatorOptions = {
		excluded:[":disabled"],
		feedbackIcons: {
			valid: 'glyphicon glyphicon-ok',
			invalid: 'glyphicon glyphicon-remove',
			validating: 'glyphicon glyphicon-refresh'
		},
		fields: {
//			userNameFrom:{
//				trigger:"change",
//				validators: {
//					notEmpty: {
//						message: '请选择用户'
//					}
//				}
//			},
			callMaxTimes: {
				validators: {
					callback:{
						callback:function(value,validator,$field){
	                  		if(value){
	                  			var regNumber = /^\+?[1-9][0-9]*$/;
								if(regNumber.test(value) == false){
									return{
										valid:false,
		                  				message:'请输入正整数'
									}
								}else{
		                  			return true;
		                  		}
	                  	}else{
	                  			return{
									valid:false,
	                  				message:'请输入配额上限'
								}
	                  		}
	                  	}.bind(this)
					}
				}
			},
//			interfaceNameFrom: {
//				trigger:"change",
//				validators: {
//					notEmpty: {
//						message: '请输入接口名称'
//					}
//				}
//			},
			concurrencyMaxTimes: {
				validators: {
					callback:{
						callback:function(value,validator,$field){
	                  		if(value){
								if(!(/^\+?[1-9][0-9]*$/.test(value))){
									return{
										valid:false,
		                  				message:'请输入正整数'
									}
								}else{
		                  			return true;
		                  		}
	                  		}else{
	                  			return{
									valid:false,
	                  				message:'请输入并发峰值'
								}
	                  		}
	                  	}.bind(this)
					}
				}
			},
		}
	}
	tableData:any[] = []; //table数据
	totalCount:number = 0; //分页总条数
	curPage:number = 1; //分页当前页
	pageSize:number = 10; //内置的分页每页条数
	tableSearch:any = {
		searchKey:''
	}
	userList:any; //用户数据
	userName:string = ''; //用户ID
	userId='';		//用户ID
	interfaceList = [];		//接口List
	interfaceData:any = [];
	interfaceName:string = '';
	interfaceId:string = '';		//接口ID
	startTime ='';		//开始时间
	endTime ='';		//结束时间
	userLimitFrom:any  = {
		id:null,
		interfaceId:'',
		interfaceName:'',		//接口
		userName:'',		//用户名
		userId:'',
		callMaxTimes:'',		//配额上限
		concurrencyMaxTimes:'',	//并发峰值	
	}
	formType = 'new';
	
	

	constructor(private jsonApiService: JsonApiService, private router: Router, private activatedRoute: ActivatedRoute ) {
		activatedRoute.queryParams.subscribe(queryParams => {
			this.curPage = queryParams.nowPage||1;
		});
	}
	//擦除用户所选值
	delUserName(){
		this.userName = '';
		this.userId = '';
		//采用简单粗暴的方法清除;官方推荐的方法失效
		var str=$("<span class='select2-selection__placeholder'>请选择</span>");
		$('#userNameSelect2').val("");
		$("#select2-userNameSelect2-container").empty();
		$("#select2-userNameSelect2-container").attr("title","");
		$("#select2-userNameSelect2-container").prepend(str);
		this.load();
	}
	//擦除用户所选值
	delUserNameFrom(){
		this.userLimitFrom.userName = '';
		this.userLimitFrom.userId = '';
		//采用简单粗暴的方法清除;官方推荐的方法失效
		var str=$("<span class='select2-selection__placeholder'>请选择</span>");
		$('#userNameSelect2From').val("");
		$("#select2-userNameSelect2From-container").empty();
		$("#select2-userNameSelect2From-container").attr("title","");
		$("#select2-userNameSelect2From-container").prepend(str);
	}
	//擦除接口所选值
	delapi(){
		this.interfaceName = '';
		this.interfaceId = '';
		//采用简单粗暴的方法清除;官方推荐的方法失效
		var str=$("<span class='select2-selection__placeholder'>请选择</span>");
		$('#apiSelect2').val("");
		$("#select2-apiSelect2-container").empty();
		$("#select2-apiSelect2-container").attr("title","");
		$("#select2-apiSelect2-container").prepend(str);
		this.load();
	}
	//擦除接口所选值
	delApiFrom(){
		this.userLimitFrom.interfaceName = '';
		this.userLimitFrom.interfaceId = '';
		//采用简单粗暴的方法清除;官方推荐的方法失效
		var str=$("<span class='select2-selection__placeholder'>请选择</span>");
		$('#apiSelect2From').val("");
		$("#select2-apiSelect2From-container").empty();
		$("#select2-apiSelect2From-container").attr("title","");
		$("#select2-apiSelect2From-container").prepend(str);
		this.load();
	}
	//初始化select2 选项
	initSelect2User(){
		var that = this;
		System.import('script-loader!select2/dist/js/select2.min.js').then(()=>{
			System.import('assets/js/select2-zh-CN.js').then(()=>{
				$("#userNameSelect2").select2({		//用户select2
			    	language : "zh-CN",
			    	placeholder :"请选择",
			    	allowClear : true,
			    	data : this.userList,//为Select添加数据
			        templateResult: this.formatRepo
			    }).on ("select2:select", function (e){
		        	  	var data = e.params.data;
		        	  	that.userName = data.text;
		        	  	that.userId = data.id;
				});
				
				$("#userNameSelect2From").select2({		//接口select2
			    	language : "zh-CN",
			    	placeholder :"请选择",
			    	allowClear : true,
			    	data : this.userList,//为Select添加数据
			        templateResult: this.formatRepo
			    }).on ("select2:select", function (e){
		        	  	var data = e.params.data;
		        	  	that.userLimitFrom.userName = data.text;
		        	  	that.userLimitFrom.userId = data.id;
		        	  	$("#userNameFrom").val(that.userLimitFrom.userName).change();
		       });
			})
		})
	}
	initSelect2Api(){
		var that = this;
		System.import('script-loader!select2/dist/js/select2.min.js').then(()=>{
			System.import('assets/js/select2-zh-CN.js').then(()=>{
				$("#apiSelect2").select2({		//用户select2
			    	language : "zh-CN",
			    	placeholder :"请选择",
			    	allowClear : true,
			    	data : this.interfaceData,//为Select添加数据
			        templateResult: this.formatRepo
			    }).on ("select2:select", function (e){
		        	  	var data = e.params.data;
		        	  	that.interfaceName = data.text;
		        	  	that.interfaceId = data.id;
				});
				
				$("#apiSelect2From").select2({		//用户select2
			    	language : "zh-CN",
			    	placeholder :"请选择",
			    	allowClear : true,
			    	data : this.interfaceData,//为Select添加数据
			        templateResult: this.formatRepo
			    }).on ("select2:select", function (e){
		        	  	var data = e.params.data;
		        	  	that.userLimitFrom.interfaceName = data.text;
		        	  	that.userLimitFrom.interfaceId = data.id;
		        	  	$("#interfaceNameFrom").val(that.userLimitFrom.interfaceName).change();
				});
			})
		})
	}
	//select2 格式回调函数
	formatRepo (state) {
		if (!state.id) {return state.text};
		var $state = $('<span><i class="fa fa-user green"></i>&nbsp;&nbsp;' + state.text + '</span>');
		return $state;
	}
	//拉取
	initAllUser(){
		var that = this;
		return new Promise(function (resolve, reject) {
			that.jsonApiService.http("user/getUserList.html",null).subscribe(data=> {
				if(data.success){
					var userList = data.data;
		        	var selectdata = [];
		        	for(var i = 0 ; i < userList.length ; i++) {
		        		var obj = {
		        			id:userList[i].id,
		        			text:userList[i].userName,
		        		}
		        		selectdata[i] = obj;
		        	}
				}
				that.userList = selectdata;
				resolve();
			})
		})
	}

	// 拉去用户select2数据
	initAllApi(){
		var that = this;
		return new Promise(function (resolve, reject) {
			that.jsonApiService.http("apiConfig/getAllApiList.html",null).subscribe(data=> {
				if(data.success){
					var apiList = data.data;
		        	var selectdata = [],apiData = [];
		        	for(var i = 0 ; i < apiList.length ; i++) {
		        		var obj = {
		        			id:apiList[i].id,
		        			text:apiList[i].interfaceName,
		        		}
		        		var api = {
		        			id:apiList[i].interfaceKey,
		        			text:apiList[i].interfaceName,
		        		}
		        		apiData[i] = api;
		        		selectdata[i] = obj;
		        	}
				}
				that.interfaceData = selectdata;
				that.interfaceList = apiData;
				resolve();
			})
		})
	}

	// 接收子组件传递过来的数据 
	getSelectTableTime(time){
		this.startTime=time.startTime;
		this.endTime=time.endTime;
	} 
	ngOnInit(){
		this.initAllUser().then(()=>{
			this.initSelect2User();
			this.load();
		});
		this.initAllApi().then(()=>{
			this.initSelect2Api();
		})
	}
	//table刷新
    refresh(){
    	this.load();
    }
	//表格搜索
	table_search(){
		this.curPage = 1;
		this.load();
	}
	//初始化加载list数据
	load(){
		let data = {
			pageSize:this.pageSize,
			nowPage:this.curPage,
			parameters:{
				interfaceId:this.interfaceId,
				userId:this.userId,
				startTime:this.startTime,
				endTime:this.endTime,
				searchKey:common.stringTrim(this.tableSearch.searchKey)
			}
		}
		let reqdata = 'gridPager='+JSON.stringify(data);
		this.jsonApiService.http("userApiConfig/queryUserApiList.html", reqdata).subscribe(data => {
			if(data.isSuccess){
				this.tableData = data.exhibitDatas;
				this.totalCount = data.recordCount;
			}else{
				this.jsonApiService.message(data.message);
			}
		})

	}
	//删除
	delRow(row){
		this.jsonApiService.confirm_message("此操作将永久删除数据,确认要删除?").then(()=>{
			this.jsonApiService.http_obj("userApiConfig/deleteUserApiConfig.html",{id:row.id}).subscribe(data=>{
				this.jsonApiService.message(data.message);
				if(data.success){
					this.load();
				}
			})
		})
	}
	
	//分页回调
	paginate(e){
		this.curPage = e.page+1;
		this.pageSize = e.rows;
		this.load();
	}
	/*
	 * 新增
	 */
	table_add(modal){
		this.modalClose(modal);
		modal.show();
		this.formType = 'new';
	}
	/*
	 * 编辑
	 */
	editRow(row,modal){
		modal.show();
		this.userLimitFrom.id = row.id;
		this.formType = 'updata';
		this.jsonApiService.http_obj("userApiConfig/getUserApiConfig.html",{id:row.id}).subscribe(data=>{
			if(data.success){
				for(let item in this.userLimitFrom){
					this.userLimitFrom[item] = row[item];
					if(item == 'userId'){
						$('#userNameSelect2From').val(data.data.userId).trigger('change');
					}
					if(item == 'interfaceId'){
						$('#apiSelect2From').val(data.data.interfaceId).trigger('change');
					}
				}
			}
		})
	}
	/*
	 * 关闭弹窗
	 */
	modalClose(modal){
		modal.hide();
		$("#userLimitFrom").data('bootstrapValidator').resetForm();
		this.userLimitFrom.id = '';
		this.userLimitFrom.userName = '';
		this.userLimitFrom.userId = '';
		this.userLimitFrom.interfaceId = '';
		this.userLimitFrom.interfaceName = '';
		this.userLimitFrom.callMaxTimes = '';
		this.userLimitFrom.concurrencyMaxTimes = '';
		$('#userNameSelect2From').val('').trigger('change');
		$('#apiSelect2From').val('').trigger('change');
	}
	/*
	 * form提交
	 */
	userControlSubmit(modal){
		if(!this.userLimitFrom.userName&&this.formType == 'new'){
			this.jsonApiService.message('请选择用户');
			return;
		}
		if(!this.userLimitFrom.interfaceName&&this.formType == 'new'){
			this.jsonApiService.message('请选择接口');
			return;
		}
		$('#userLimitFrom').bootstrapValidator('validate'); //开启验证
		let isValid = $('#userLimitFrom').data('bootstrapValidator').isValid();  //验证是否通过
		if(isValid){
			let url;
			if(this.formType == 'new'){
				url = "userApiConfig/addUserApiConfig.html";		//新建
			}else if(this.formType == 'updata'){
				url = "userApiConfig/updateUserApiConfig.html";		//编辑
			}
			this.jsonApiService.http_obj(url,this.userLimitFrom).subscribe(data=> {
				this.jsonApiService.message(data.message);
				if(data.success){
					this.load();
					this.modalClose(modal);
				}
			})
		}
	}

}